package com.lm.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class HotCommentService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 获取当前周标识，通常用年份 + 周数表示
    private String getCurrentWeekKey() {
        return "weekly:hot:comments:" + System.currentTimeMillis() / (1000 * 60 * 60 * 24 * 7);
    }

    // 添加评论点赞数
    public void addCommentLike(String commentId) {
        String weekKey = getCurrentWeekKey();
        // Increment the like count (sorted set score) by 1
        redisTemplate.opsForZSet().incrementScore(weekKey, commentId, 1);
        // Set an expiration for the current week data (e.g., 7 days)
        redisTemplate.expire(weekKey, 7, TimeUnit.DAYS);
    }

    // 获取本周的热门评论
    public Set<String> getWeeklyHotComments(int topN) {
        String weekKey = getCurrentWeekKey();
        // 获取当前周点赞数最多的评论，按分数降序排列
        return redisTemplate.opsForZSet().reverseRange(weekKey, 0, topN - 1);
    }
}
